<?php

namespace app\data\util;

class Upload
{
    protected $fileName;
    protected $fileInfo;
    protected $maxSize;
    protected $allowExt;
    protected $allowMime;
    protected $uploadPath;
    protected $imgFlag;
    protected $img_url;
    private $Error;
    private $Ext;



    public function __construct($fileName='file', $uploadPath='/upload/file/', $maxSize = '629145600', $allowExt = ['jpg', 'jpeg', 'png', 'git', 'doc', 'xls', 'xlsx','csv','pdf','zip','rar','docx','xlsm'])
    {
        $this->fileName = $fileName;
        $this->getFileInfo();
        $this->maxSize = $maxSize;
        $this->allowExt = $allowExt;
        $this->uploadPath = $uploadPath;
        $this->img_url = getDomain().'/public' .$uploadPath;
    }

    public function getFileInfo()
    {
        if (isset($_FILES[$this->fileName]) && $_FILES[$this->fileName]){
            $this->fileInfo = $_FILES[$this->fileName];
        }else{
            return ['status' => 0, 'error' => '未找到上传文件，请检查是否上传文件、fileName名称'];
        }

    }

    public function getFileSize()
    {
        return $this->fileInfo['size'];
    }

    //产生唯一字符串
    protected function getUniname(){
        return md5(uniqid(microtime(true),true));
    }

    protected function getFileName($name, $use_old=true){
        if($use_old){
            $old_name = explode('.', $this->fileInfo['name']);
            $name = $old_name[0];
        }
        return $name.'_'.date('Ymd_His').'.'.$this->Ext;
    }

    //上传文件
    public function upload($name='listing'){
        if($this->fileInfo && $this->checkError() && $this->checkSize() && $this->checkExt() && $this->checkHTTPpost())
        {
            $this->checkuploadPath();
            $file_name = $this->getFileName($name,false);
            //如果存在中文文件名需要转码
            $name =  iconv('UTF-8', 'GBK//IGNORE', $file_name);
            $file_path = $this->uploadPath.$name;
            if(move_uploaded_file($this->fileInfo['tmp_name'] , getDomain() .$file_path)){
                return [
                    'status'    => 1,
                    'file_url'  => $this->img_url.$file_name,
                    'file_path' => $this->uploadPath.$file_name,
                    'file_name' => $file_name,
                    'file_size' => $this->getFileSize(),
                    'upload_name'=>$this->fileInfo['name']
                ];
            }else{
                $this->Error = '移动文件失败'.$this->fileInfo['tmp_name'].'<br/>'. FCPATH.$file_path.'<br/>'.$this->uploadPath.'<br/>'.json_encode($this->fileInfo).'<br/>'.$_FILES['file']['error'] ;
                return $this->showError();
            }
        }else{
            return $this->showError();
        }
    }

    //上传excel文件
    public function uploadExcel($name='listing'){
        if($this->fileInfo && $this->checkError() && $this->checkSize() && $this->checkExt() && $this->checkHTTPpost())
        {
            $this->checkuploadPath();
            $file_name = $this->getFileName($name,false);
            $file_path = $this->uploadPath.$file_name;

            if(move_uploaded_file($this->fileInfo['tmp_name'] ,  FCPATH.$file_path)){
                return [
                    'status'    => 1,
                    'file_url'  => $this->img_url.$file_name,
                    'file_path' => $file_path,
                    'file_name' => $file_name,
                    'file_size' => $this->getFileSize(),
                    'upload_name'=>$this->fileInfo['name']
                ];
            }else{
                $this->Error = '移动文件失败'.$this->fileInfo['tmp_name'].'<br/>'. FCPATH.$file_path.'<br/>'.$this->uploadPath.'<br/>'.json_encode($this->fileInfo).'<br/>'.$_FILES['file']['error'] ;
                return $this->showError();
            }
        }else{
            return $this->showError();
        }
    }

    //检测目录是否存在，创建目录
    protected function checkuploadPath(){
        if(!file_exists(FCPATH.$this->uploadPath)){
            @mkdir(FCPATH.$this->uploadPath,0777,true);
        }
    }
    //检测文件大小
    public function checkSize(){
        if($this->fileInfo['size'] > $this->maxSize){
            $this->Error = $this->fileInfo['name'].'文件过大,不能大于'.$this->maxSize.'字节';
            return false;
        }
        return true;
    }

    //检测是否通过HTTP、POST方式上传
    protected function checkHTTPpost(){
        if(!is_uploaded_file($this->fileInfo['tmp_name'])){
            $this->Error = '不是通过HTTP、POST方式上传的';
            return false;
        }
        return true;
    }

    //显示错误
    protected function showError(){
        return  [
            'status' => 0,
            'error' => empty($this->Error) ? '未获取到文件信息' : $this->Error
        ];
    }

    //检测文件拓展名
    public function checkExt(){
        $this->Ext = strtolower(pathinfo($this->fileInfo['name'],PATHINFO_EXTENSION));
        if(!in_array($this->Ext,$this->allowExt)){
            $allowExt_str = '';
            if(!empty($this->allowExt))
                $allowExt_str = implode(',',$this->allowExt);
            $this->Error = '不允许的拓展名,支持的文件为'.$allowExt_str;
            return false;
        }
        return true;
    }

    //是否检测图片类型
    protected function imgTure(){
        if($this->imgFlag){
            if(!getimagesize($this->fileInfo['tmp_name'])){
                $this->Error = '不是真实图片';
                return false;
            }
            return true;
        }
    }

    //检测文件格式
    public function checkMime(){
        if(!in_array($this->fileInfo['type'],$this->allowMime)){
            $this->Error = '不允许的图片类型';
            return false;
        }
        return true;
    }


    //检测是否有错
    public function checkError(){
        if(!is_null($this->fileInfo['error'])){
            if($this->fileInfo['error'] > 0){
                switch ($this->fileInfo['error']) {
                    case 1:
                        $this->Error = '上传文件超过了配置文件中upload_max_filesize选项的值';
                        break;
                    case 2:
                        $this->Error = '超过表单MAX_FILE_SIZE限制的大小';
                        break;
                    case 3:
                        $this->Error = '文件上传不完整';
                        break;
                    case 4:
                        $this->Error = '没有选择上传文件';
                        break;
                    case 6:
                        $this->Error = '没有找到临时目录';
                        break;
                    case 7:
                        $this->Error = '文件不可写';
                        break;
                    case 8:
                        $this->Error = '由于PHP的扩展程序中断文件上传';
                        break;

                }
                return false;
            }else{
                return true;
            }
        }else{
            $this->Error = '文件上传出错';
            return false;
        }
    }
}